import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/views/Layout'
import Login from '@/views/Login'
import Detail from '@/views/Detail'
import Register from '@/views/Register'
import House from '@/views/House'
import Index from '@/views/Index'
import Information from '@/views/Information'
import User from '@/views/User'
import Collect from '@/views/Collect'
import Location from '@/views/Location'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/index',
    children: [
      { path: '/index', component: Index },
      { path: '/house', component: House },
      { path: '/information', component: Information },
      { path: '/user', component: User }
    ]
  },
  { path: '/login', component: Login },
  { path: '/detail/:id', component: Detail },
  { path: '/register', component: Register },
  { path: '/collect', component: Collect },
  { path: '/location', component: Location }
]

const router = new VueRouter({
  routes
})

const whileList = ['/login', '/register', '/user', '/index']
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next()
  } else {
    if (whileList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
